package com.yufuchang;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by yufuchang on 2020/9/5.
 */
@RestController
public class ExchangeController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("get_exchange")
    public void getExchange(){
        String url = "http://jsonplaceholder.typicode.com/posts/5";
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET,
                null, String.class);
        String body = responseEntity.getBody(); // 获取响应体
        HttpStatus statusCode = responseEntity.getStatusCode(); // 获取响应码
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 获取响应码值
        HttpHeaders headers = responseEntity.getHeaders(); // 获取响应头

        System.out.println("body：" + body);
        System.out.println("statusCode：" + statusCode);
        System.out.println("statusCodeValue：" + statusCodeValue);
        System.out.println("headers：" + headers);
        return;
    }

    @GetMapping("post_exchange")
    public void postExchange(){
// 请求地址
        String url = "http://jsonplaceholder.typicode.com/posts";

        // 请求头设置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        //提交参数设置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userId", "666");
        map.add("title", "afeawfa");
        map.add("body", "测试信息");

        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);

        // 发送post请求，并输出结果
        ResponseEntity<String> responseEntity
                = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        String body = responseEntity.getBody(); // 获取响应体
        HttpStatus statusCode = responseEntity.getStatusCode(); // 获取响应码
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 获取响应码值
        HttpHeaders responseHeaders = responseEntity.getHeaders(); // 获取响应头

        System.out.println("body：" + body);
        System.out.println("statusCode：" + statusCode);
        System.out.println("statusCodeValue：" + statusCodeValue);
        System.out.println("headers：" + responseHeaders);
    }
}
